package br.com.transitojp.controller;

import javax.persistence.NoResultException;
import org.hibernate.HibernateException;
import br.com.transitojp.dao.DaoUser;
import br.com.transitojp.dao.HibernateUtil;
import br.com.transitojp.model.User;

public class UserControl {
	
	public User validateLogin(String login, String password){
		
		DaoUser daoUser = new DaoUser(HibernateUtil.getSessionFactory().openSession());
		User userLogged;
		
		try {
			userLogged = daoUser.validateLogin(login, password);
		} catch (NoResultException e) {
			userLogged = null;
		}catch (HibernateException e) {
			System.out.println(e);
			userLogged = null;
		}finally{
			daoUser.getSession().close();
		}
		
		return userLogged;
	}
	
	public static void createAdmin(User admin) {
		DaoUser userDao = new DaoUser(HibernateUtil
				.getSessionFactory().openSession());
		userDao.getSession().beginTransaction();
		User user = new User();
		try {
			user = userDao.findByLogin("Admin");
			if (user == null) {
				userDao.makePersistent(admin);
			}
		} catch (Exception e) {
		}
		userDao.getSession().getTransaction().commit();
		userDao.getSession().close();
	}

}
